<script setup>
import FriendsSvg from "@/components/svg/FriendsSvg.vue";
import FriendList from "@/pages/friend/components/FriendList.vue";
import {host_custom} from "@/host.js";
import axios from "axios";
import {onMounted, onUnmounted, ref} from "vue";
import {userStore} from "@/stores/userStore.js";
import { useSocket } from "@/socket.js";
import { useFriendStore } from "@/stores/friendStore.js";
import { storeToRefs } from "pinia";

const { friendList } = storeToRefs(useFriendStore())
const { storeGetFriendList } = useFriendStore()




const userAction = userStore()
const { userInfo } = userAction

const searchThings = ref('')
const searchResult = ref([])
let searchDelay
async function searchHandle() {
  if (searchThings.value === '') {
    searchResult.value.length = 0
    return false
  }
  clearTimeout(searchDelay)
  searchDelay = setTimeout(async ()=>{
    const res = await axios.get(host_custom + '/searchFriends', {params: {searchThing: searchThings.value}})
    searchResult.value = res.data
  },800)
}

const onLineFriends = ref([])

const handleFriendOnline = (fid) => {
  // onlineElement.value.play();
  friendList.value.forEach((item) => {
    if (item.id === fid) item.isOnline = true;
  });
};

const handleFriendAlreadyOnline = (onlineFriends) => {
  friendList.value = friendList.value.map((friend) => {
    if (onlineFriends.includes(friend.id)) return { ...friend, isOnline: true };
    return friend;
  });
};

const handleFriendOffline = (id) => {
  // offlineElement.value.play();
  friendList.value.forEach((item) => {
    if (item.id === id) item.isOnline = false;
  });
};

onMounted(async () => {
  useSocket().on("friendOnline", handleFriendOnline);
  useSocket().on("friendAlreadyOnline", handleFriendAlreadyOnline);
  useSocket().on("friend_offline", handleFriendOffline);
  useSocket().on('friendAlreadyOnline', friends => {
    onLineFriends.value = friends
  })


  await storeGetFriendList()
  useSocket().emit('getOnlineFriends', friendList.value)
});



onUnmounted(() => {
  useSocket().off("friendOnline", handleFriendOnline);
  useSocket().off("friendAlreadyOnline", handleFriendAlreadyOnline);
  useSocket().off("friend_offline", handleFriendOffline);
});

</script>

<template>
    <div class="friendSearchWrapper p-2 d-flex flex-column flex-grow-1">
      <ul class="nav nav-tabs d-flex flex-nowrap flex-shrink-0" id="friendListTab" role="tablist">
        <li class="nav-item flex-shrink-0">
          <button class="nav-link disabled"><FriendsSvg/>&ensp;<span>好友</span></button>
        </li>
        <li class="nav-item flex-shrink-0" role="presentation">
          <button class="nav-link text-secondary active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">在线</button>
        </li>
        <li class="nav-item flex-shrink-0" role="presentation">
          <button class="nav-link text-secondary" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">全部</button>
        </li>
        <li class="nav-item flex-shrink-0 text-secondary">
          <button class="mt-1 ms-2 btn btn-sm btn-primary" id="addFriend-tab" data-bs-toggle="tab" data-bs-target="#addFriend" type="button" >添加好友</button>
        </li>
      </ul>


      <div class="tab-content flex-grow-1" id="friendTabContent">
        <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
          <friend-list :friend-list="friendList" :list-filter="`online`"/>
        </div>

        <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
          <friend-list :friend-list="friendList" :list-filter="`all`"/>
        </div>

        <div class="tab-pane fade" id="addFriend" role="tabpanel" aria-labelledby="addFriend-tab">
          <div>
            <h5 class="text-body-emphasis my-3">添加好友</h5>
            <p class="mb-3">你可以通过搜索用户名来添加他们</p>
            <div class="input-group mb-3">
              <input type="text" @input="searchHandle" v-model.trim="searchThings" class="form-control" placeholder="用户名" aria-label="用户名" aria-describedby="basic-addon2">
              <span class="input-group-text" id="basic-addon2"><font-awesome-icon :icon="['fas', 'magnifying-glass']" /></span>
            </div>
          </div>

          <div class="resultFrame">
            <div class="my-2 small" v-show="searchResult.length>0">找到{{searchResult.length}}条结果</div>

            <div class="userListResult">
              <template v-for="val of searchResult">
                <router-link v-if="userInfo.id!==val.id" :to="`/checkUserProfile/${val.id}`" class="text-decoration-none text-secondary-emphasis fw-bold">
                  <div class="searchResult d-flex align-items-center justify-content-between p-2">
                    <div>
                      <img class="rounded-circle" :src="host_custom+'/pfp/'+val.avatar" width="36px" height="36px" :alt="val.name">
                      <span class="px-2">{{val.name}}</span>
                    </div>

                    <span>用户</span>
                  </div>
                </router-link>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
</template>

<style scoped>
#friendListTab {
  overflow-y: clip;
  overflow-x: scroll; scrollbar-width: none
}

.nav-link.active {
  font-weight: bold;
  color: var(--bs-secondary-text-emphasis) !important;
}

.userListResult {

}

.friendSearchWrapper {
  overflow: hidden;
}

#friendTabContent {
  overflow-y: auto;
}


.searchResult{
  transition: none;
}
.searchResult:hover {
  border-radius: 8px;
  background-color: var(--bs-tertiary-bg);
}
</style>